package com.example.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 使用数据库保存用户信息以及读取信息方式
 * 跳转到相对应的页面
 */
//@Configuration
public class WebSecurityConfig3 extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);

//        auth.inMemoryAuthentication().withUser("admin").authorities("admin","root")
//        .password(passwordEncoder.encode("123456"))
//        .and()
//        .withUser("user").authorities("user").password(passwordEncoder.encode("123456"));

        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //开启httpBasic
        http.httpBasic().and();
        //关闭跨域
        http.csrf().disable();

        //设置自定义登录页面
        http.formLogin()
                .loginPage("/login.html")// 自定义登录页面路径
                // 自定义页面的登录路径，注意要与登录页面的action值一致，<form action="/authentication/form" method="post">
                .loginProcessingUrl("/authentication/form")
                //默认security的登录页面的action为/login
//                .loginProcessingUrl("/login")
                .failureUrl("/login/error")
                .and()
                .authorizeRequests() // 定义哪些URL需要被保护、哪些不需要被保护
                //设置放路径，login.html页面如果不放行则报错将您重定向的次数过多
                .antMatchers("/login.html").permitAll()
                .antMatchers("/login/error").permitAll()
                .antMatchers("/js/**", "/css/**", "/images/**", "/fronts/**").permitAll()

                //设置路径需要权限访问
                .antMatchers("/users","/home","/others").hasAnyAuthority("ROLE_USER")
                //读取配置权限配置
                .antMatchers("/**").access("hasRole('ADMIN')")

                // 其余请求都需要身份验证
                .anyRequest().authenticated();


    }

    //认证密码  通过BCrypt加密 检验解密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }



}
